<template>
    <!--过度-->
    <transition>
        <!--  显示隐藏-->
        <div @click="toTop" v-show="topShow" class="me-to-top">
            <i class="el-icon-caret-top"></i>
        </div>
    </transition>
</template>

<script>
    export default {
        name: 'GoTop',
        data() {
            return {
                topShow: false
            }
        },
        methods: {
            //滚动到最上面
            toTop() {
                document.body.scrollTop = 0;
                document.documentElement.scrollTop = 0;
                this.topShow = false;
            },
            //当前高度>400，就显示
            needToTop() {
    /*          document.documentElement.scrollTop来获取垂直滚动的偏移值，
                document.documentElement.scrollLeft来获取水平滚动的偏移值。*/
                //                                                兼容
                let curHeight = document.documentElement.scrollTop || document.body.scrollTop;
                if (curHeight > 200) {
                    this.topShow = true;
                } else {
                    this.topShow = false;
                }

            }
        },

        mounted() {
            /**
             * 等到整个视图都渲染完毕
             */
            this.$nextTick(function () {
                //滚动的时候触发方法判断
                window.addEventListener('scroll', this.needToTop);
            });
        }
    }
</script>

<style>
    .me-to-top {
    background-color: #fff;
    position: fixed;
    right: 100px;
    bottom: 150px;
    width: 40px;
    height: 40px;
    border-radius: 20px;
    cursor: pointer;
    transition: .3s;
    box-shadow: 0 0 6px rgba(0, 0, 0, .12);
    z-index: 5;
    }

    .me-to-top i {
    color: #00d1b2;
    display: block;
    line-height: 40px;
    text-align: center;
    font-size: 18px;
    }

</style>

